﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace BlockingIO
{
    public class BIOTcpClient : BIO
    {
        public TcpClient TcpClient;
        private IPEndPoint endPoint;

        public BIOTcpClient(string hostname, int port)
        {
            this.endPoint = new IPEndPoint(IPAddress.Parse(hostname), port);
            this.FunctionTryConnect = this.TcpTryConnect;
        }

        private bool TcpTryConnect()
        {
            if (this.TcpClient != null && TcpClient.Client != null && this.TcpClient.Connected)
                return true;

            try
            {
                if (this.TcpClient != null)
                    this.TcpClient.Close();

                this.TcpClient = new TcpClient();
                this.TcpClient.Connect(this.endPoint);

                return true;
            }
            catch (Exception err)
            {
                return false;
            }
        }
    }
}
